package com.xm.settlement.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import com.xm.settlement.commons.base.ApiSQLException;
import com.xm.settlement.commons.shiro.ShiroUser;
import com.xm.settlement.commons.utils.*;
import com.xm.settlement.model.PageData;
import com.xm.settlement.model.User;
import com.xm.settlement.model.UserRole;
import com.xm.settlement.mapper.UserRoleMapper;
import com.xm.settlement.model.vo.AppUserVo;
import com.xm.settlement.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xm.settlement.mapper.UserMapper;
import com.xm.settlement.model.vo.UserVo;
import com.xm.settlement.service.IUserService;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * User 表数据服务层接口实现类
 *
 */
@Service
public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private AppUserService appUserService;

    @Override
    public List<User> selectByLoginName(UserVo userVo)    {
        User user = new User();
        user.setLoginName(userVo.getLoginName());
        EntityWrapper<User> wrapper = new EntityWrapper<User>(user);
        if (null != userVo.getId()) {
            wrapper.where("id != {0}", userVo.getId());
        }
        return this.selectList(wrapper);
    }

    @Override
    public void insertByVo(UserVo userVo,ShiroUser shiroUser) throws InterruptedException, URISyntaxException, ApiSQLException, UnsupportedEncodingException {
        User user = BeanUtils.copy(userVo, User.class);
        user.setCreateTime(new Date());
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        this.insert(user);

        Long id = user.getId();
        String[] roles = userVo.getRoleIds().split(",");
        UserRole userRole = new UserRole();

        for (String string : roles) {
            userRole.setUserId(id);
            userRole.setRoleId(Long.valueOf(string));
            userRoleMapper.insert(userRole);
        }
        SendSMS sendSMS = new SendSMS();
        //--- 添加到表 app_user app_manage
        AppUserVo appUserVo = new AppUserVo();
        appUserVo.setVip_code(userVo.getPhone());
        appUserVo.setName(userVo.getName());
        String password = UUID.randomUUID().toString().substring(0,8);
        appUserVo.setPassword(DigestUtils.md5Hex(password));
        appUserVo.setPhone(Long.valueOf(userVo.getPhone()));
        appUserVo.setStatus(1);
        appUserVo.setCreate_time(new Date());
        // todo push_code 平台自己创建的上级推荐人是谁
        UserVo userVo1 = selectVoById(shiroUser.getId());
        appUserVo.setPush_code(null);
        appUserVo.setService_code(userVo1.getPhone());
        //appUserVo.set

        try{
            appUserService.insertAppUser(appUserVo,userVo.getId());
            sendSMS.sendAccount(userVo.getPhone(),password);
        }catch (Exception e){
            e.printStackTrace();

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ApiSQLException(1101,e.getMessage());
        }
    }

    @Override
    public UserVo selectVoById(Long id) {
        return userMapper.selectUserVoById(id);
    }

    @Override
    public void updateByVo(UserVo userVo) {
        User user = BeanUtils.copy(userVo, User.class);
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        }else{
            userVo.setPassword(DigestUtils.md5Hex(userVo.getPassword()));
        }
        this.updateSelectiveById(user);

        Long id = userVo.getId();
        List<UserRole> userRoles = userRoleMapper.selectByUserId(id);
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRole userRole : userRoles) {
                userRoleMapper.deleteById(userRole.getId());
            }
        }

        String[] roles = userVo.getRoleIds().split(",");
        UserRole userRole = new UserRole();
        for (String string : roles) {
            userRole.setUserId(id);
            userRole.setRoleId(Long.valueOf(string));
            userRoleMapper.insert(userRole);
        }
        //-- 修改 appuser appusermanage
        //查询出来修改
       /* AppUser appUser = new AppUser();
        appUser.setVip_code(userVo.getLoginName());
        appUser = appUserService.selectOne(appUser);
        if(appUser == null ){
            return;
        }
        AppUserVo appUserVo = BeanUtils.copy(appUser,AppUserVo.class);
        appUserVo.setVip_code(userVo.getPhone());
        appUserVo.setName(userVo.getName());
        SendSMS sendSMS = new SendSMS();
        String password = sendSMS.sendAccount(userVo.getPhone());
        if(password == null){
            return ;
        }else{
            appUserVo.setPassword(DigestUtils.md5Hex( password ));
        }
*/
    }

    @Override
    public void updatePwdByUserId(Long userId, String md5Hex) {
        User user = new User();
        user.setId(userId);
        user.setPassword(md5Hex);
        this.updateSelectiveById(user);
    }

    @Override
    public void selectDataGrid(PageInfo pageInfo) {
        Page<UserVo> page = new Page<UserVo>(pageInfo.getNowpage(), pageInfo.getSize());
        List<UserVo> list = userMapper.selectUserVoPage(page, pageInfo.getCondition());
        pageInfo.setRows(list);
        pageInfo.setTotal(page.getTotal());
    }

    @Override
    public void deleteUserById(Long id) {
        this.deleteById(id);
        List<UserRole> userRoles = userRoleMapper.selectByUserId(id);
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRole userRole : userRoles) {
                userRoleMapper.deleteById(userRole.getId());
            }
        }
    }

    @Override
    public void insertByteArrayToFile(MultipartFile multiFile, HttpServletRequest request) throws Exception {

            /*------------------------上传文件到服务器-------------------------*/
            String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;								//文件上传路径
            String fileName =  FileUpload.fileUp(multiFile, filePath, System.currentTimeMillis()+"_User");
           /*------------------执行读EXCEL并添加到数据库-------------------------------*/
        List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName , 2, 0, 0);	//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
             /*存入数据库操作======================================*/
        PageData pd = new PageData();

        /**
         * var0 :编号
         * var1 :登录名
         * var2 :姓名
         * var3 :性别
         * var4 :年龄
         * var5 :电话
         */

        AtomicInteger atomicInteger = new AtomicInteger(0);
        for(int i=0;i<listPd.size();i++){

            String login_name = listPd.get(i).getString("var1");

            if(atomicInteger.intValue() > 0 && login_name == "" ){
                break;
            }

            if (login_name == "" ){
                throw new RuntimeException("第"+(i+3)+"行登录名为空");
            }
            if(userMapper.findForObject(login_name) != null){
                throw new RuntimeException("登录名已经重复");
            }

            pd.put("login_name", login_name);
            String name = listPd.get(i).getString("var2");
            if(name == "" ){
                throw new RuntimeException("第"+(i+3)+"行用户名为空");
            }
            pd.put("name",name);


            String sex = listPd.get(i).getString("var3");                       //性别
            if (sex.equals("男")){

                pd.put("sex", 1);
            }else {
                pd.put("sex", 0);
            }

            String sAge = listPd.get(i).getString("var4");
            if (sAge == ""){
                sAge = "0";
            }
            pd.put("age",Integer.parseInt(sAge));	 //年龄


            String phone = listPd.get(i).getString("var5");
            if(phone == ""){
                throw new RuntimeException("第"+(i+2)+"行电话号码为空");
            }
            pd.put("phone", Long.parseLong(phone.trim()));	                         //手机号

            pd.put("user_type", 1);					                                 //默认角色 销售员
            pd.put("organization_id", 7);				                             //默认部门 服务中心
            pd.put("status", 0);					                                 //状态
            pd.put("password",DigestUtils.md5Hex("123"));	                     //默认密码123

            userMapper.insertU(pd);


            Long user_id = userMapper.selectLastId();
            UserRole userRole = new UserRole();
            userRole.setUserId(user_id);
            userRole.setRoleId(Long.valueOf(9));
            userRoleMapper.insert(userRole);
            atomicInteger.addAndGet(0);
        }
    }
}